package net.pingfang.devicelock;

import lombok.extern.slf4j.Slf4j;
import net.pingfang.util.HexUtil;
import org.springframework.integration.ip.tcp.serializer.AbstractPooledBufferByteArraySerializer;
import org.springframework.integration.ip.tcp.serializer.SoftEndOfStreamException;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

@Slf4j
public class TestSerializer extends AbstractPooledBufferByteArraySerializer {

    public TestSerializer() {
    }

    public byte[] doDeserialize(InputStream inputStream, byte[] buffer) throws IOException {
        int n = this.fillToCrLf(inputStream, buffer);
        return this.copyToSizedArray(buffer, n);
    }

    public int fillToCrLf(InputStream inputStream, byte[] buffer) throws IOException {
        int n = 0;
        boolean sign = true;//首位标志 55 69
        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Available to read: " + inputStream.available());
        }

        try {
            do {
                int bite = inputStream.read();
                if (bite < 0 && n == 0) {
                    throw new SoftEndOfStreamException("Stream closed between payloads");
                }
                this.checkClosure(bite);
                if (n > 0 && bite == 69 && buffer[n - 1] == 55) {
                    if(sign){
                        sign = false;
                    }else{
                        buffer[n++] = 69;
                        n++;
                        return n - 1;
                    }
                }
                buffer[n++] = (byte)bite;
            } while(n < this.getMaxMessageSize());
            throw new IOException("没有找到隔离符 7E，最大长度：" + this.getMaxMessageSize());
        } catch (SoftEndOfStreamException var6) {
            throw var6;
        } catch (IOException | RuntimeException var7) {
            this.publishEvent(var7, buffer, n);
            throw var7;
        }
    }

    public void serialize(byte[] bytes, OutputStream outputStream) throws IOException {
        outputStream.write(bytes);
    }
}
